package com.example.gulimall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.common.constant.SearchConstant;
import com.example.common.to.es.SkuEsModel;
import com.example.common.config.es.GulimallElasticsearchConfig;
import com.example.gulimall.search.service.ProductSaveService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        if (CollectionUtils.isEmpty(skuEsModels)) {
            log.error("商品上架失败，es接收数据为：{}", JSONObject.toJSONString(skuEsModels));
            return false;
        }

        // 1. 创建索引，建立映射关系
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            /*String json = JSON.toJSONString(model).concat("\n");
            byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
            bulkRequest.add(new BytesArray(bytes),
                    SearchConstant.PRODUCT_INDEX, SearchConstant.PRODUCT_TYPE, XContentType.JSON);*/

            if (Objects.isNull(model)) {
                continue;
            }

            ObjectMapper mapper = new ObjectMapper();
            //对象转map
            Map m = mapper.readValue(mapper.writeValueAsString(model), Map.class);

            IndexRequest req = new IndexRequest()
                    .index(SearchConstant.PRODUCT_INDEX)
                    .id(String.valueOf(model.getSkuId()))
                    .source(m, XContentType.JSON);

            bulkRequest.add(req);
        }

        // 2. 索引中保存数据
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        if (bulk.hasFailures()) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            log.info("商品上架失败!");
            List<String> collect = Arrays.stream(bulk.getItems()).map(
                    BulkItemResponse::getId
            ).collect(Collectors.toList());
            log.info("错误数据ID：{}", JSONObject.toJSONString(collect));
            log.error("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        }
        // true: 有错误  false: 无错误
        return bulk.hasFailures();
    }
}
